﻿using AFanDa.BLL.BaseService;
using AFanDa.Dto.Base;
using AFanDa.Dto.Request;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AFanDa.BLL.BLLService
{
    public class CardService
    {
        BaseCardsService _baseCardsService = null;
        BaseCardDetialsService _baseCardDetialsService = null;
        public CardService()
        {
            _baseCardsService = new BaseCardsService();
            _baseCardDetialsService = new BaseCardDetialsService();

        }


        /// <summary>
        /// 新增卡券
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public ApiResult AddCard(CardRequestDto dto)
        {
            Dto.EF.Cards card = new Dto.EF.Cards()
            {
                CID = Common.Config.GUID(),
                CName = dto.name,
                CBeginTime = DateTime.Parse(dto.begin),
                CEndTime = DateTime.Parse(dto.end),
                CCount = dto.count,
                CCreateTime = DateTime.Now,
                CExplain = dto.explain,
                CParam1 = dto.param1,
                CParam2 = dto.param2,
                CType = dto.type,
                CIsBan = 0,
                CIsPublish = 0,
            };
            _baseCardsService.Add(card);
            var result = _baseCardsService.SaveChange();
            if (result > 0)
            {

                return new ApiResult()
                {
                    code = ApiCode.ok,
                    message = "添加成功"
                };
            }

            return new ApiResult()
            {
                code = ApiCode.fail,
                message = "添加失败"
            };

        }


        /// <summary>
        /// 获取单张卡券详情
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public ApiResult GetSingleCard(CardRequestDto dto)
        {
            var iq = _baseCardsService.QueryAll(d => d.CID == dto.id);
            if (iq.Any() == false)
            {
                //参数错误 并return
            }

            var data = iq.Select(d => new Dto.Reponse.CardResponseDto
            {
                id = d.CID,
                name = d.CName,
                count = d.CCount,
                lqCount = d.CardDetails.Count(),
                useCount = d.CardDetails.Where(e => e.CDIsUse == 1).Count(),
                type = d.CType,
                param1 = d.CParam1,
                param2 = d.CParam2,
                explain = d.CExplain,
                begin = d.CBeginTime.Value,//这里写的方法 必须是sqlserver中存在的才可以 
                end = d.CEndTime.Value,
                isPublish = d.CIsPublish,
                isBan = d.CIsBan,
                createTime = d.CCreateTime.Value,
                details = d.CardDetails.Select(e => new Dto.Reponse.CardDetailsResponseDto
                {
                    id = e.CDID,
                    card = e.CDNumber,
                    cid = e.CDCID,
                    account = e.WxUser.UPhone,
                    name = e.WxUser.UName,
                    isUse = e.CDIsUse,
                    createTime = e.CDCreateTime.Value,
                }).ToList()
            }).SingleOrDefault();



            return new ApiResult()
            {
                code = ApiCode.ok,
                message = "获取卡券详情",
                data = data


            };

        }



        /// <summary>
        /// 获取卡券列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public ApiResult GetCards(CardRequestDto dto)
        {
            dto.key = dto.key ?? "";
            var iq = _baseCardsService.QueryAll(out int total, dto.page, dto.limit,
                o => o.CCreateTime, false, d => d.CName.Contains(dto.key));
            var data = iq.Select(d => new Dto.Reponse.CardResponseDto
            {
                id = d.CID,
                name = d.CName,
                count = d.CCount,
                lqCount = d.CardDetails.Count(),
                useCount = d.CardDetails.Where(e => e.CDIsUse == 1).Count(),
                type = d.CType,
                param1 = d.CParam1,
                param2 = d.CParam2,
                explain = d.CExplain,
                begin = d.CBeginTime.Value,//这里写的方法 必须是sqlserver中存在的才可以 
                end = d.CEndTime.Value,
                isPublish = d.CIsPublish,
                isBan = d.CIsBan,
                createTime = d.CCreateTime.Value
            }).ToList();

            return new ApiResult()
            {
                code = ApiCode.ok,
                data = new
                {
                    data = data,
                    total = total
                },

                message = "获取卡券列表"
            };
        }


        /// <summary>
        /// 领取优惠券
        /// </summary>
        /// <returns></returns>
        public ApiResult GainCard(CardRequestDto dto)
        {
            var now = DateTime.Now;
            var iq = _baseCardsService.QueryAll(d => d.CID == dto.id && d.CIsPublish == 1 && d.CIsBan == 0
              && d.CBeginTime < now && d.CEndTime > now);
            if (!iq.Any())
            {
                return new ApiResult()
                {
                    code = ApiCode.fail,
                    message = "参数错误"
                };
            }
            var iq2 = _baseCardDetialsService.QueryAll(d => d.CDCID == dto.id
              && d.CDEID == dto.uid);
            if (iq2.Any())
            {
                return new ApiResult()
                {
                    code = ApiCode.fail,
                    message = "已经领取过该优惠券"
                };
            }
            //如果有,则还需要判断是否存在领取资格
            //当前优惠券是有数量限制的 如果优惠券已经领完了 是不是也不能领取
            var card = iq.Single();
            if (card.CardDetails.Count >= card.CCount)
            {
                return new ApiResult()
                {
                    code = ApiCode.fail,
                    message = "券已抢完"
                };
            }
            Dto.EF.CardDetails detail = new Dto.EF.CardDetails()
            {
                CDID = Common.Config.GUID(),
                CDEID = dto.uid,
                CDNumber = Common.Config.GUID(),
                CDCID = dto.id,
                CDIsUse = 0,
                CDCreateTime = DateTime.Now,
                CDUserOrder = null,
            };
            _baseCardDetialsService.Add(detail);
            var result = _baseCardDetialsService.SaveChange();
            return new ApiResult()
            {
                code = ApiCode.ok,
                message = "领取成功"
            };

        }



    }
}
